/*
 * @Author: Await
 * @Date: 2025-05-11 14:30:00
 * @LastEditors: Await
 * @LastEditTime: 2025-05-11 14:30:00
 * @Description: 数据缩放组件配置
 */
import React, { useState } from 'react';
import {
    Form,
    Input,
    Switch,
    Select,
    InputNumber,
    Row,
    Col,
    Typography,
    Tooltip,
    ColorPicker,
    Divider,
    Slider,
    Space,
    Card,
    Tabs,
    Radio
} from 'antd';
import { InfoCircleOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import type { DataZoomConfig as DataZoomConfigType } from '../../types/chartTypes';
import type { RadioChangeEvent } from 'antd';

const { Option } = Select;
const { TabPane } = Tabs;

interface DataZoomConfigProps {
    value?: DataZoomConfigType | DataZoomConfigType[];
    onChange: (value: DataZoomConfigType | DataZoomConfigType[]) => void;
    multiple?: boolean; // 是否允许多个DataZoom实例
}

/**
 * 数据区域缩放组件配置
 * 
 * 用于设置ECharts的dataZoom属性，可以控制图表的缩放和平移
 * 支持slider和inside两种类型的配置
 */
const DataZoomConfig: React.FC<DataZoomConfigProps> = ({
    value,
    onChange,
    multiple = false
}) => {
    // 默认配置
    const defaultConfig: DataZoomConfigType = {
        show: true,
        type: 'slider',
        start: 0,
        end: 100,
        xAxisIndex: 0,
        orient: 'horizontal'
    };

    // 处理值为空的情况
    let config: DataZoomConfigType | DataZoomConfigType[] = value || defaultConfig;

    // 如果开启了多个实例，但当前值不是数组，转换为数组
    if (multiple && !Array.isArray(config)) {
        config = [config];
    }

    // 如果没有开启多个实例，但当前值是数组，取第一个
    if (!multiple && Array.isArray(config)) {
        config = config[0] || defaultConfig;
    }

    // 当前选中的配置索引（用于多实例时）
    const [activeIndex, setActiveIndex] = useState(0);

    // 根据multiple参数获取当前的配置
    const getCurrentConfig = (): DataZoomConfigType => {
        if (multiple && Array.isArray(config)) {
            return config[activeIndex] || defaultConfig;
        }
        return config as DataZoomConfigType;
    };

    // 获取当前配置
    const currentConfig = getCurrentConfig();

    // 表单项标题组件
    const FormItemLabel = ({ children, tooltip }: { children: React.ReactNode, tooltip?: string }) => (
        <div style={{ marginBottom: 4, display: 'flex', alignItems: 'center' }}>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                {children}
            </Typography.Text>
            {tooltip && (
                <Tooltip title={tooltip}>
                    <InfoCircleOutlined style={{ marginLeft: 4, fontSize: 12, color: '#999' }} />
                </Tooltip>
            )}
        </div>
    );

    // 处理配置变更
    const handleConfigChange = (key: string, value: any) => {
        // 处理嵌套属性
        const updateConfig = (target: DataZoomConfigType, path: string, val: any): DataZoomConfigType => {
            if (path.includes('.')) {
                const [first, ...rest] = path.split('.');
                const nested = target[first] || {};
                return {
                    ...target,
                    [first]: updateConfig(nested as DataZoomConfigType, rest.join('.'), val)
                };
            }
            return { ...target, [path]: val };
        };

        if (multiple && Array.isArray(config)) {
            // 更新数组中特定索引的配置
            const newConfig = [...config];
            newConfig[activeIndex] = updateConfig(newConfig[activeIndex], key, value);
            onChange(newConfig);
        } else {
            // 直接更新单个配置
            onChange(updateConfig(config as DataZoomConfigType, key, value));
        }
    };

    // 添加新的DataZoom实例
    const handleAddDataZoom = () => {
        if (multiple && Array.isArray(config)) {
            const newConfig = [...config, { ...defaultConfig }];
            onChange(newConfig);
            setActiveIndex(newConfig.length - 1);
        }
    };

    // 删除DataZoom实例
    const handleDeleteDataZoom = (index: number) => {
        if (multiple && Array.isArray(config) && config.length > 1) {
            const newConfig = config.filter((_, i) => i !== index);
            onChange(newConfig);
            setActiveIndex(Math.min(activeIndex, newConfig.length - 1));
        }
    };

    // 处理类型变更
    const handleTypeChange = (e: RadioChangeEvent) => {
        handleConfigChange('type', e.target.value);

        // 根据类型设置一些默认值
        if (e.target.value === 'inside') {
            handleConfigChange('show', false);
        } else {
            handleConfigChange('show', true);
        }
    };

    return (
        <div style={{ padding: 12, background: '#fff', borderRadius: 4 }}>
            {/* 预览效果 */}
            <Card
                size="small"
                title="数据缩放效果预览"
                style={{ marginBottom: 16 }}
                bodyStyle={{
                    height: 100,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    position: 'relative',
                    backgroundColor: '#f5f5f5',
                    borderRadius: 2
                }}
            >
                {/* 简单的DataZoom效果预览 */}
                <div style={{
                    width: '80%',
                    position: 'relative',
                    height: currentConfig.type === 'slider' ? 60 : 40,
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center'
                }}>
                    {/* 数据线 */}
                    <div style={{
                        height: 2,
                        backgroundColor: '#ddd',
                        width: '100%',
                        position: 'relative'
                    }} />

                    {/* 缩放框 - 仅在slider类型时显示 */}
                    {currentConfig.type === 'slider' && (
                        <div style={{
                            position: 'absolute',
                            height: currentConfig.orient === 'horizontal' ? 20 : '100%',
                            width: currentConfig.orient === 'horizontal' ? '100%' : 20,
                            bottom: currentConfig.orient === 'horizontal' ? -25 : 'auto',
                            right: currentConfig.orient === 'horizontal' ? 'auto' : -25,
                            backgroundColor: '#f0f0f0',
                            border: '1px solid #d9d9d9',
                            borderRadius: 4
                        }}>
                            {/* 选择区域 */}
                            <div style={{
                                position: 'absolute',
                                left: `${currentConfig.start || 0}%`,
                                right: `${100 - (currentConfig.end || 100)}%`,
                                top: 4,
                                bottom: 4,
                                backgroundColor: currentConfig.fillerColor || '#b3e5fc',
                                borderRadius: 2
                            }} />

                            {/* 手柄-左 */}
                            <div style={{
                                position: 'absolute',
                                left: `${currentConfig.start || 0}%`,
                                top: 2,
                                width: 10,
                                height: 16,
                                backgroundColor: '#fff',
                                border: '1px solid #1890ff',
                                borderRadius: 3,
                                transform: 'translateX(-50%)',
                                cursor: 'ew-resize'
                            }} />

                            {/* 手柄-右 */}
                            <div style={{
                                position: 'absolute',
                                left: `${currentConfig.end || 100}%`,
                                top: 2,
                                width: 10,
                                height: 16,
                                backgroundColor: '#fff',
                                border: '1px solid #1890ff',
                                borderRadius: 3,
                                transform: 'translateX(-50%)',
                                cursor: 'ew-resize'
                            }} />
                        </div>
                    )}

                    {/* 针对inside类型显示的提示 */}
                    {currentConfig.type === 'inside' && (
                        <div style={{
                            position: 'absolute',
                            width: '100%',
                            textAlign: 'center',
                            color: '#999',
                            fontSize: 12,
                            top: 10
                        }}>
                            内置型缩放（滚轮或拖拽操作）
                        </div>
                    )}
                </div>
            </Card>

            {/* 多实例选择器 */}
            {multiple && Array.isArray(config) && (
                <Card size="small" style={{ marginBottom: 16 }}>
                    <Space style={{ marginBottom: 8 }}>
                        <Typography.Text>数据缩放实例:</Typography.Text>
                        <Select
                            value={activeIndex}
                            onChange={setActiveIndex}
                            style={{ width: 120 }}
                            dropdownRender={menu => (
                                <>
                                    {menu}
                                    <Divider style={{ margin: '4px 0' }} />
                                    <Button
                                        type="text"
                                        icon={<PlusOutlined />}
                                        block
                                        onClick={handleAddDataZoom}
                                    >
                                        添加新实例
                                    </Button>
                                </>
                            )}
                        >
                            {config.map((_, index) => (
                                <Option key={index} value={index}>
                                    DataZoom {index + 1}
                                </Option>
                            ))}
                        </Select>

                        {config.length > 1 && (
                            <Button
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                                onClick={() => handleDeleteDataZoom(activeIndex)}
                            >
                                删除
                            </Button>
                        )}
                    </Space>
                </Card>
            )}

            {/* 配置表单 */}
            <Tabs defaultActiveKey="basic">
                <TabPane tab="基础设置" key="basic">
                    <Row gutter={[16, 16]}>
                        <Col span={12}>
                            <FormItemLabel tooltip="数据缩放组件类型">
                                数据缩放类型
                            </FormItemLabel>
                            <Radio.Group
                                value={currentConfig.type || 'slider'}
                                onChange={handleTypeChange}
                                buttonStyle="solid"
                                style={{ width: '100%' }}
                            >
                                <Radio.Button value="slider" style={{ width: '50%', textAlign: 'center' }}>
                                    滑动条型
                                </Radio.Button>
                                <Radio.Button value="inside" style={{ width: '50%', textAlign: 'center' }}>
                                    内置型
                                </Radio.Button>
                            </Radio.Group>
                        </Col>

                        {currentConfig.type === 'slider' && (
                            <Col span={12}>
                                <FormItemLabel tooltip="是否显示滑动条">
                                    显示滑动条
                                </FormItemLabel>
                                <Switch
                                    checked={currentConfig.show !== false}
                                    onChange={value => handleConfigChange('show', value)}
                                />
                            </Col>
                        )}

                        <Col span={12}>
                            <FormItemLabel tooltip="控制哪个X轴，可以设为单个轴或多个轴">
                                控制X轴
                            </FormItemLabel>
                            <Select
                                value={currentConfig.xAxisIndex === 'all' ? 'all' : (currentConfig.xAxisIndex || 0)}
                                onChange={value => handleConfigChange('xAxisIndex', value)}
                                style={{ width: '100%' }}
                            >
                                <Option value="all">全部</Option>
                                <Option value={0}>X轴 1</Option>
                                <Option value={1}>X轴 2</Option>
                            </Select>
                        </Col>

                        <Col span={12}>
                            <FormItemLabel tooltip="控制哪个Y轴，可以设为单个轴或多个轴">
                                控制Y轴
                            </FormItemLabel>
                            <Select
                                value={currentConfig.yAxisIndex === 'all' ? 'all' : (currentConfig.yAxisIndex || 0)}
                                onChange={value => handleConfigChange('yAxisIndex', value)}
                                style={{ width: '100%' }}
                            >
                                <Option value="all">全部</Option>
                                <Option value={0}>Y轴 1</Option>
                                <Option value={1}>Y轴 2</Option>
                            </Select>
                        </Col>

                        <Col span={12}>
                            <FormItemLabel tooltip="滑动条方向">
                                方向
                            </FormItemLabel>
                            <Radio.Group
                                value={currentConfig.orient || 'horizontal'}
                                onChange={e => handleConfigChange('orient', e.target.value)}
                                buttonStyle="solid"
                                style={{ width: '100%' }}
                            >
                                <Radio.Button value="horizontal" style={{ width: '50%', textAlign: 'center' }}>
                                    水平
                                </Radio.Button>
                                <Radio.Button value="vertical" style={{ width: '50%', textAlign: 'center' }}>
                                    垂直
                                </Radio.Button>
                            </Radio.Group>
                        </Col>

                        {currentConfig.type === 'inside' && (
                            <>
                                <Col span={12}>
                                    <FormItemLabel tooltip="如何触发缩放。可取值为true，false，'shift'，'ctrl'，'alt'">
                                        鼠标滚轮缩放
                                    </FormItemLabel>
                                    <Select
                                        value={currentConfig.zoomOnMouseWheel === false ? 'false' : (currentConfig.zoomOnMouseWheel || true)}
                                        onChange={value => handleConfigChange('zoomOnMouseWheel', value === 'false' ? false : value)}
                                        style={{ width: '100%' }}
                                    >
                                        <Option value={true}>开启</Option>
                                        <Option value="shift">按住Shift键</Option>
                                        <Option value="ctrl">按住Ctrl键</Option>
                                        <Option value="alt">按住Alt键</Option>
                                        <Option value="false">关闭</Option>
                                    </Select>
                                </Col>

                                <Col span={12}>
                                    <FormItemLabel tooltip="如何触发数据窗口平移。可取值为true，false，'shift'，'ctrl'，'alt'">
                                        鼠标拖拽平移
                                    </FormItemLabel>
                                    <Select
                                        value={currentConfig.moveOnMouseMove === false ? 'false' : (currentConfig.moveOnMouseMove || true)}
                                        onChange={value => handleConfigChange('moveOnMouseMove', value === 'false' ? false : value)}
                                        style={{ width: '100%' }}
                                    >
                                        <Option value={true}>开启</Option>
                                        <Option value="shift">按住Shift键</Option>
                                        <Option value="ctrl">按住Ctrl键</Option>
                                        <Option value="alt">按住Alt键</Option>
                                        <Option value="false">关闭</Option>
                                    </Select>
                                </Col>
                            </>
                        )}
                    </Row>
                </TabPane>

                <TabPane tab="范围设置" key="range">
                    <Row gutter={[16, 16]}>
                        <Col span={24}>
                            <FormItemLabel tooltip="数据窗口范围的起始百分比，0 - 100">
                                数据窗口范围
                            </FormItemLabel>
                            <Row gutter={8}>
                                <Col span={11}>
                                    <InputNumber
                                        value={currentConfig.start || 0}
                                        onChange={value => handleConfigChange('start', value)}
                                        min={0}
                                        max={currentConfig.end ? currentConfig.end - 1 : 99}
                                        style={{ width: '100%' }}
                                        addonAfter="%"
                                    />
                                </Col>
                                <Col span={2} style={{ textAlign: 'center', lineHeight: '32px' }}>
                                    <span>至</span>
                                </Col>
                                <Col span={11}>
                                    <InputNumber
                                        value={currentConfig.end || 100}
                                        onChange={value => handleConfigChange('end', value)}
                                        min={currentConfig.start ? currentConfig.start + 1 : 1}
                                        max={100}
                                        style={{ width: '100%' }}
                                        addonAfter="%"
                                    />
                                </Col>
                            </Row>
                            <Slider
                                range
                                value={[currentConfig.start || 0, currentConfig.end || 100]}
                                onChange={value => {
                                    handleConfigChange('start', value[0]);
                                    handleConfigChange('end', value[1]);
                                }}
                                min={0}
                                max={100}
                                style={{ marginTop: 8 }}
                            />
                        </Col>

                        <Col span={12}>
                            <FormItemLabel tooltip="是否锁定选择区域的大小">
                                锁定缩放
                            </FormItemLabel>
                            <Switch
                                checked={currentConfig.zoomLock === true}
                                onChange={value => handleConfigChange('zoomLock', value)}
                            />
                        </Col>

                        <Col span={12}>
                            <FormItemLabel tooltip="数据过滤模式">
                                数据过滤模式
                            </FormItemLabel>
                            <Select
                                value={currentConfig.filterMode || 'filter'}
                                onChange={value => handleConfigChange('filterMode', value)}
                                style={{ width: '100%' }}
                            >
                                <Option value="filter">过滤掉数据窗口外的数据点</Option>
                                <Option value="weakFilter">弱过滤模式</Option>
                                <Option value="empty">替换为空值</Option>
                                <Option value="none">不过滤，只改变坐标轴范围</Option>
                            </Select>
                        </Col>

                        <Col span={12}>
                            <FormItemLabel tooltip="距离数据窗口10%的范围内会被自动吸附">
                                范围吸附
                            </FormItemLabel>
                            <Switch
                                checked={currentConfig.rangeMode ? true : false}
                                onChange={value => handleConfigChange('rangeMode', value ? ['value', 'value'] : undefined)}
                            />
                        </Col>
                    </Row>
                </TabPane>

                {currentConfig.type === 'slider' && (
                    <TabPane tab="样式设置" key="style">
                        <Row gutter={[16, 16]}>
                            <Col span={12}>
                                <FormItemLabel tooltip="背景颜色">
                                    背景颜色
                                </FormItemLabel>
                                <ColorPicker
                                    value={currentConfig.backgroundColor || '#eee'}
                                    onChange={value => handleConfigChange('backgroundColor', value.toHexString())}
                                    style={{ width: '100%' }}
                                />
                            </Col>

                            <Col span={12}>
                                <FormItemLabel tooltip="选定范围内填充的颜色">
                                    填充颜色
                                </FormItemLabel>
                                <ColorPicker
                                    value={currentConfig.fillerColor || '#b3e5fc'}
                                    onChange={value => handleConfigChange('fillerColor', value.toHexString())}
                                    style={{ width: '100%' }}
                                />
                            </Col>

                            <Col span={12}>
                                <FormItemLabel tooltip="边框颜色">
                                    边框颜色
                                </FormItemLabel>
                                <ColorPicker
                                    value={currentConfig.borderColor || '#ddd'}
                                    onChange={value => handleConfigChange('borderColor', value.toHexString())}
                                    style={{ width: '100%' }}
                                />
                            </Col>

                            <Col span={12}>
                                <FormItemLabel tooltip="边框宽度">
                                    边框宽度
                                </FormItemLabel>
                                <InputNumber
                                    value={currentConfig.borderWidth || 1}
                                    onChange={value => handleConfigChange('borderWidth', value)}
                                    min={0}
                                    max={10}
                                    style={{ width: '100%' }}
                                    addonAfter="px"
                                />
                            </Col>

                            <Col span={24}>
                                <FormItemLabel tooltip="布局位置">
                                    布局位置
                                </FormItemLabel>
                                <Row gutter={8}>
                                    <Col span={12}>
                                        <Input
                                            addonBefore="左"
                                            value={currentConfig.left || '5%'}
                                            onChange={e => handleConfigChange('left', e.target.value)}
                                            placeholder="auto"
                                        />
                                    </Col>
                                    <Col span={12}>
                                        <Input
                                            addonBefore="上"
                                            value={currentConfig.top || 'auto'}
                                            onChange={e => handleConfigChange('top', e.target.value)}
                                            placeholder="auto"
                                        />
                                    </Col>
                                </Row>
                                <Row gutter={8} style={{ marginTop: 8 }}>
                                    <Col span={12}>
                                        <Input
                                            addonBefore="右"
                                            value={currentConfig.right || 'auto'}
                                            onChange={e => handleConfigChange('right', e.target.value)}
                                            placeholder="auto"
                                        />
                                    </Col>
                                    <Col span={12}>
                                        <Input
                                            addonBefore="下"
                                            value={currentConfig.bottom || '5%'}
                                            onChange={e => handleConfigChange('bottom', e.target.value)}
                                            placeholder="auto"
                                        />
                                    </Col>
                                </Row>
                            </Col>

                            <Col span={12}>
                                <FormItemLabel tooltip="组件宽度">
                                    宽度
                                </FormItemLabel>
                                <Input
                                    value={currentConfig.width || 'auto'}
                                    onChange={e => handleConfigChange('width', e.target.value)}
                                    placeholder="auto"
                                    addonAfter="px/%"
                                />
                            </Col>

                            <Col span={12}>
                                <FormItemLabel tooltip="组件高度">
                                    高度
                                </FormItemLabel>
                                <Input
                                    value={currentConfig.height || 'auto'}
                                    onChange={e => handleConfigChange('height', e.target.value)}
                                    placeholder="auto"
                                    addonAfter="px/%"
                                />
                            </Col>
                        </Row>
                    </TabPane>
                )}
            </Tabs>
        </div>
    );
};

export default DataZoomConfig; 